/**
 * 上传工具类
 */

/**
 * 上传图片
 * @param {string} filePath - 文件路径
 * @param {string} token - 用户token
 * @returns {Promise} 上传结果
 */
export const uploadImage = (filePath, token = '') => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: '/api/common/uploadImg',
			filePath: filePath,
			name: 'images',
			header: {
				'Authorization': token || uni.getStorageSync('token') || ''
			},
			success: (res) => {
				try {
					const result = JSON.parse(res.data);
					if (result.code == 1) {
						resolve(result);
					} else {
						reject(new Error(result.msg || '上传失败'));
					}
				} catch (error) {
					reject(new Error('解析上传结果失败'));
				}
			},
			fail: (error) => {
				reject(new Error('上传失败'));
			}
		});
	});
};

/**
 * 选择并上传图片
 * @param {Object} options - 选择图片的选项
 * @param {number} options.count - 选择数量，默认1
 * @param {Array} options.sizeType - 尺寸类型，默认['compressed']
 * @param {Array} options.sourceType - 来源类型，默认['album', 'camera']
 * @returns {Promise} 上传结果
 */
export const chooseAndUploadImage = async (options = {}) => {
	const {
		count = 1,
		sizeType = ['compressed'],
		sourceType = ['album', 'camera']
	} = options;

	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType,
			sourceType,
			success: async (res) => {
				try {
					const filePath = res.tempFilePaths[0];
					const result = await uploadImage(filePath);
					resolve(result);
				} catch (error) {
					reject(error);
				}
			},
			fail: (error) => {
				reject(new Error('选择图片失败'));
			}
		});
	});
};

/**
 * 批量上传图片
 * @param {Array} filePaths - 文件路径数组
 * @param {string} token - 用户token
 * @returns {Promise} 上传结果数组
 */
export const uploadMultipleImages = async (filePaths, token = '') => {
	const uploadPromises = filePaths.map(filePath => uploadImage(filePath, token));
	return Promise.all(uploadPromises);
}; 